﻿using BLL;
using Common.Middlewares;
using Common.Regexs;
using Entity.Models.Entities;
using IBLL;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RepositorySys.Filte;
using RepositorySys.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using utils;
using utils.enums;
using utils.EX;
using Utils;
using Utils.enums;

namespace RepositorySys.Controllers
{
    [CustomActionFilte]
    public class UserController : Controller
    {

        /// <summary>
        /// 用户列表视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult Indexssss()
        {
            return View();
        }

        /// <summary>
        /// 添加视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            return View();
        }

        /// <summary>
        /// 修改视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit()
        {
            return View();
        }

        /// <summary>
        /// 修改用户密码视图
        /// </summary>
        /// <returns></returns>
        public IActionResult EditPwdView()
        {
            return View();
        }
        /// <summary>
        /// 修改基本信息视图
        /// </summary>
        /// <returns></returns>
        public IActionResult UserSetting()
        {
            return View();
        }

        IUserBLL userBLL;

        private readonly RequestDelegate _next;  // 用来处理上下文请求  
        private readonly ILogger<ExceptionHandlingMiddleware> _logger;
        public UserController(IUserBLL userBLL, ILogger<ExceptionHandlingMiddleware> logger)
        {
            this.userBLL = userBLL;
            this._logger = logger;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Upload(IFormFile file)
        {
            //获取登录
            string userId = HttpContext.Session.GetString("userId");
            object data = null;
            try
            {
                if (string.IsNullOrEmpty(userId))
                {
                    throw new MyException(500, "登录已过期");
                }
                 data=   userBLL.UploadAvatar(userId, file);
            }
            catch (MyException e)
            {
                return getException(data, e);
            }

            return Json(new JsonResults(0, "上传成功", 200 , data));
        }

        //测试全局异常
        [HttpGet]
        public IActionResult GetUsers()
        {
            _logger.LogInformation("Get User Details");

            //try
            //{
            //    throw new KeyNotFoundException("Get User failed"); // 此处抛出一个KeyNotFoundException异常

            //}
            //catch (Exception)
            //{

            //    throw;
            //}

             throw new KeyNotFoundException("Get User failed");

        }

        /// <summary>
        /// 根据用户id查询用户信息
        /// </summary>
        /// <returns></returns>
        public JsonResult getbyUserId()
        {
            string userid = HttpContext.Session.GetString("userId");
            return Json(new JsonResults(200, Enums.getDescribe(SettingEnums.Json_STATE.SUCCESS), userBLL.getbyUserId(userid)));
        }

        /// <summary>
        ///获取用户信息(头像)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult getUserIcon()
        {
            string userId= HttpContext.Session.GetString("userId");
            return Json(new JsonResults(200, Enums.getDescribe(SettingEnums.Json_STATE.SUCCESS), userBLL.getUserIcon(userId)));
        }

     

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="old_password">旧密码</param>
        /// <param name="new_password">新密码</param>
        /// <param name="again_password">确定密码</param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdataPassword(string old_password, string new_password, string again_password)
        {
            string userid = HttpContext.Session.GetString("userId");
            object data = null;
            try
            {
                data = userBLL.UpdataPassword(old_password, new_password, again_password, userid);
            }
            catch (MyException e)
            {
                return getException(data, e);
            }
            //清除Session
            HttpContext.Session.Remove("userId");
            HttpContext.Session.Remove("userName");
            return Json(new JsonResults(200, Enums.getDescribe(UserEnums.USER_STATE.UPDATE), data));
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddUser(UserInfo userInfo)
        {
            object data = null;
            string mgs = null;
            if (Verify(userInfo, out mgs))
            {
                try
                {
                    data = userBLL.AddUser(userInfo);
                }
                catch (MyException e)
                {
                    return getException(data, e);
                }
            }
            return Json(new JsonResults(200, mgs == null ? Enums.getDescribe(UserEnums.USER_STATE.SUCCESS) : mgs, data));
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DatateUser(string userId)
        {
            object data = null;
            try
            {
                data = userBLL.DatateUser(userId);
            }
            catch (MyException e)
            {
                return getException(data, e);
            }
            return Json(new JsonResults(200, Enums.getDescribe(UserEnums.USER_STATE.DATATE), data));
        }


        /// <summary>
        /// 用户信息列表、搜索
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult UserShow(string userName, string page, string limit)
        {
            int cont;
            List<UserInfoDTO> userInfos = userBLL.userShow(userName, page, limit, out cont);
            return Json(new JsonResults(0, Enums.getDescribe(SettingEnums.Json_STATE.SUCCESS), cont, userInfos));
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DatateUsers(List<String> userIds)
        {
            object data = null;
            try
            {
                data = userBLL.DatateUsers(userIds);
            }
            catch (MyException e)
            {
                return getException(data, e);
            }
            return Json(new JsonResults(200, Enums.getDescribe(UserEnums.USER_STATE.DATATE), data));
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdateUser(UserInfo user)
        {
            object data = null;
            string mgs = null;
            if (Verify(user, out mgs))
            {
                try
                {
                    data = userBLL.UpdateUser(user);
                }
                catch (MyException e)
                {
                    //返回异常信息
                    return getException(data, e);
                }
            }
            return Json(new JsonResults(200, mgs == null ? Enums.getDescribe(UserEnums.USER_STATE.UPDATE) : mgs, data));
        }

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public JsonResult byUser(string account)
        {
            return Json(new JsonResults(0, Enums.getDescribe(SettingEnums.Json_STATE.SUCCESS), 1000, userBLL.byUserUser(account)));
        }
        /// <summary>
        /// 参数验证
        /// </summary>
        /// <param name="consumableInfo">参数</param>
        /// <returns></returns>
        private bool Verify(UserInfo user, out string mgs)
        {
            if (!new Regex(Regular.Name).Match(user.UserName).Success)
            {
                mgs = "请输入正确的名称";
                return false;
            }
            else if (!new Regex(Regular.Phone).Match(user.PhoneNum).Success)
            {
                mgs = "请输入正确的手机号";
                return false;
            }
            else if (user.Account!=null? !new Regex(Regular.PassWord).Match(user.Account).Success:false)
            {
                mgs = "请输入正确的账号";
                return false;
            }
            else if (user.PassWord != null ? !new Regex(Regular.PassWord).Match(user.PassWord).Success : false)
            {
                mgs = "请输入正确的密码";
                return false;
            }
            else if (!new Regex(Regular.Email).Match(user.Email).Success)
            {
                mgs = "请输入正确的邮箱";
                return false;
            }
            mgs = null;
            return true;
        }
        /// <summary>
        /// 获取异常
        /// </summary>
        /// <param name="data"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private IActionResult getException(object data, MyException e)
        {
            var tt = e.GetExceptionResult();
            return Json(new JsonResults(tt.resultStatus, tt.resultMsg, data));
        }
    }
}
